package dao;

import com.ny.demo524.SqlConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
   //注册
    public int addUser(String username,String password) throws SQLException {
        Connection connection = SqlConnection.getCon();
        String sql = "insert into users(username,password) values(?,?);";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);
        return preparedStatement.executeUpdate();
    }
    public Users login (String username,String password) throws SQLException {
        Users users = null;
        Connection connection = SqlConnection.getCon();
        String sql = "select * from users where username = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            users = new Users();
            users.setId(resultSet.getInt("id"));
            users.setUsername(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));

        }
        return users;
    }
    public Users delete(int id) throws SQLException {
        Users users = null;
        Connection connection = SqlConnection.getCon();
        String sql = "delete from users where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);
        int i = preparedStatement.executeUpdate();
        if (i > 0) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
        return users;
    }
    public Users update(int id,String username) throws SQLException {
        Users users = null;
        Connection connection = SqlConnection.getCon();
        String sql = "update users set username = ? where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString (1, username);
        preparedStatement.setInt (2, id);
        int i =  preparedStatement.executeUpdate();
        if(i>0){
            System.out.println("修改用户名成功");
        }else{
            System.out.println("修改用户名失败");
        }
        return users;
    }
}


